from apscheduler.schedulers.blocking import BlockingScheduler
from modules import NewsCollector, CompanyDatabase, NewsAnalyzer, TradingStrategy
import time
import concurrent.futures
import traceback
from utils import logger, alert_system

def daily_job():
    try:
        # 添加性能监控
        start_time = time.time()
        logger.info("开始执行每日任务")
        
        # 异步执行各模块
        with concurrent.futures.ThreadPoolExecutor() as executor:
            news_future = executor.submit(NewsCollector().fetch_news)
            db_future = executor.submit(CompanyDatabase)
            
            news = news_future.result(timeout=300)  # 5分钟超时
            db = db_future.result(timeout=60)
        
        # 2. 分析新闻
        analyzer = NewsAnalyzer()
        analysis_results = []
        
        for title, content in news:
            analysis = analyzer.analyze_news(content)
            related_companies = db.find_similar(
                industry=analysis['industry'],
                market_cap_range=(1e9, 5e10)  # 示例参数
            )
            analysis_results.append({
                **analysis,
                'related_companies': related_companies
            })
        
        # 3. 生成策略
        strategy = TradingStrategy().generate_daily_strategy(analysis_results)
        
        # 4. 输出结果
        send_email_report(strategy)
        save_to_database(strategy)
        
    except Exception as e:
        logger.error(f"任务执行失败: {traceback.format_exc()}")
        alert_system.send(f"任务异常: {str(e)}")
    finally:
        logger.info(f"任务完成，耗时{time.time()-start_time:.2f}秒")

if __name__ == '__main__':
    scheduler = BlockingScheduler()
    scheduler.add_job(daily_job, 'cron', day_of_week='mon-fri', hour=8, minute=45)
    scheduler.start() 